namespace DotNetNuke.Services.Upgrade
{
    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Data;
    using DotNetNuke.Entities.Host;
    using DotNetNuke.Entities.Modules;
    using DotNetNuke.Entities.Modules.Definitions;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Tabs;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Framework.Providers;
    using DotNetNuke.Modules.Admin.ResourceInstaller;
    using DotNetNuke.Security;
    using DotNetNuke.Security.Permissions;
    using DotNetNuke.Security.Roles;
    using DotNetNuke.Services.Exceptions;
    using DotNetNuke.Services.FileSystem;
    using DotNetNuke.Services.Log.EventLog;
    using DotNetNuke.Services.Personalization;
    using DotNetNuke.Services.Scheduling;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.Data;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Web;
    using System.Web.Profile;
    using System.Web.Security;
    using System.Xml;

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The Upgrade class provides Shared/Static methods to Upgrade/Install
    /// a DotNetNuke Application
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// [cnurse]	11/6/2004	documented
    /// </history>
    /// -----------------------------------------------------------------------------
    public class Upgrade
    {
        private static DateTime startTime;
        private static bool upgradeMemberShipProvider = true;

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddAdminPage adds an Admin Tab Page
        /// </summary>
        /// <param name="Portal">The Portal</param>
        /// <param name="TabName">The Name to give this new Tab</param>
        /// <param name="TabIconFile">The Icon for this new Tab</param>
        /// <param name="IsVisible">A flag indicating whether the tab is visible</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static DotNetNuke.Entities.Tabs.TabInfo AddAdminPage(PortalInfo Portal, string TabName, string TabIconFile, bool IsVisible)
        {
            DotNetNuke.Entities.Tabs.TabInfo AdminPage = new TabController().GetTab(Portal.AdminTabId);
            TabPermissionCollection objTabPermissions = new TabPermissionCollection();
            AddPagePermission(ref objTabPermissions, "View", Convert.ToInt32(Portal.AdministratorRoleId));
            return AddPage(AdminPage, TabName, TabIconFile, IsVisible, objTabPermissions, true);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals
        /// </summary>
        /// <param name="TabName">The Name to give this new Tab</param>
        /// <param name="TabIconFile">The Icon for this new Tab</param>
        /// <param name="IsVisible">A flag indicating whether the tab is visible</param>
        /// <param name="ModuleDefId">The Module Deinition Id for the module to be aded to this tab</param>
        /// <param name="ModuleTitle">The Module's title</param>
        /// <param name="ModuleIconFile">The Module's icon</param>
        /// <history>
        /// [cnurse]	11/16/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddAdminPages(string TabName, string TabIconFile, bool IsVisible, int ModuleDefId, string ModuleTitle, string ModuleIconFile)
        {
            AddAdminPages(TabName, TabIconFile, IsVisible, ModuleDefId, ModuleTitle, ModuleIconFile, true);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals
        /// </summary>
        /// <param name="TabName">The Name to give this new Tab</param>
        /// <param name="TabIconFile">The Icon for this new Tab</param>
        /// <param name="IsVisible">A flag indicating whether the tab is visible</param>
        /// <param name="ModuleDefId">The Module Deinition Id for the module to be aded to this tab</param>
        /// <param name="ModuleTitle">The Module's title</param>
        /// <param name="ModuleIconFile">The Module's icon</param>
        /// <param name="InheritPermissions">Modules Inherit the Pages View Permisions</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddAdminPages(string TabName, string TabIconFile, bool IsVisible, int ModuleDefId, string ModuleTitle, string ModuleIconFile, bool InheritPermissions)
        {
            ArrayList arrPortals = new PortalController().GetPortals();
            int refIntHelperL0 = arrPortals.Count - 1;
            for (int intPortal = 0; intPortal <= refIntHelperL0; intPortal++)
            {
                PortalInfo objPortal = (PortalInfo) arrPortals[intPortal];
                AddModuleToPage(AddAdminPage(objPortal, TabName, TabIconFile, IsVisible), ModuleDefId, ModuleTitle, ModuleIconFile, InheritPermissions);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddHostPage adds a Host Tab Page
        /// </summary>
        /// <param name="TabName">The Name to give this new Tab</param>
        /// <param name="TabIconFile">The Icon for this new Tab</param>
        /// <param name="IsVisible">A flag indicating whether the tab is visible</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static DotNetNuke.Entities.Tabs.TabInfo AddHostPage(string TabName, string TabIconFile, bool IsVisible)
        {
            DotNetNuke.Entities.Tabs.TabInfo HostPage = new TabController().GetTabByName("Host", Null.NullInteger);
            TabPermissionCollection objTabPermissions = new TabPermissionCollection();
            AddPagePermission(ref objTabPermissions, "View", Convert.ToInt32("-2"));
            return AddPage(HostPage, TabName, TabIconFile, IsVisible, objTabPermissions, true);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleControl adds a new Module Control to the system
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="ModuleDefId">The Module Definition Id</param>
        /// <param name="ControlKey">The key for this control in the Definition</param>
        /// <param name="ControlTitle">The title of this control</param>
        /// <param name="ControlSrc">Te source of ths control</param>
        /// <param name="IconFile">The icon file</param>
        /// <param name="ControlType">The type of control</param>
        /// <param name="ViewOrder">The vieworder for this module</param>
        /// <history>
        /// [cnurse]	11/08/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddModuleControl(int ModuleDefId, string ControlKey, string ControlTitle, string ControlSrc, string IconFile, SecurityAccessLevel ControlType, int ViewOrder)
        {
            AddModuleControl(ModuleDefId, ControlKey, ControlTitle, ControlSrc, IconFile, ControlType, ViewOrder, Null.NullString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleControl adds a new Module Control to the system
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="ModuleDefId">The Module Definition Id</param>
        /// <param name="ControlKey">The key for this control in the Definition</param>
        /// <param name="ControlTitle">The title of this control</param>
        /// <param name="ControlSrc">Te source of ths control</param>
        /// <param name="IconFile">The icon file</param>
        /// <param name="ControlType">The type of control</param>
        /// <param name="ViewOrder">The vieworder for this module</param>
        /// <param name="HelpURL">The Help Url</param>
        /// <history>
        /// [cnurse]	11/08/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddModuleControl(int ModuleDefId, string ControlKey, string ControlTitle, string ControlSrc, string IconFile, SecurityAccessLevel ControlType, int ViewOrder, string HelpURL)
        {
            ModuleControlController objModuleControls = new ModuleControlController();
            if (objModuleControls.GetModuleControlByKeyAndSrc(ModuleDefId, ControlKey, ControlSrc) == null)
            {
                ModuleControlInfo objModuleControl = new ModuleControlInfo();
                objModuleControl.ModuleControlID = Null.NullInteger;
                objModuleControl.ModuleDefID = ModuleDefId;
                objModuleControl.ControlKey = ControlKey;
                objModuleControl.ControlTitle = ControlTitle;
                objModuleControl.ControlSrc = ControlSrc;
                objModuleControl.ControlType = ControlType;
                objModuleControl.ViewOrder = ViewOrder;
                objModuleControl.IconFile = IconFile;
                objModuleControl.HelpURL = HelpURL;
                objModuleControls.AddModuleControl(objModuleControl);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleDefinition adds a new Core Module Definition to the system
        /// </summary>
        /// <remarks>
        /// This overload asumes the module is an Admin module and not a Premium Module
        /// </remarks>
        /// <param name="DesktopModuleName">The Friendly Name of the Module to Add</param>
        /// <param name="Description">Description of the Module</param>
        /// <param name="ModuleDefinitionName">The Module Definition Name</param>
        /// <returns>The Module Definition Id of the new Module</returns>
        /// <history>
        /// [cnurse]	10/14/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static int AddModuleDefinition(string DesktopModuleName, string Description, string ModuleDefinitionName)
        {
            return AddModuleDefinition(DesktopModuleName, Description, ModuleDefinitionName, false, true, Null.NullString, Null.NullString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleDefinition adds a new Core Module Definition to the system
        /// </summary>
        /// <remarks>
        /// This overload allows the caller to determine whether the module is an Admin module 
        /// or a Premium Module
        /// </remarks>
        /// <param name="DesktopModuleName">The Friendly Name of the Module to Add</param>
        /// <param name="Description">Description of the Module</param>
        /// <param name="ModuleDefinitionName">The Module Definition Name</param>
        /// <param name="Premium">A flag representing whether the module is a Premium module</param>
        /// <param name="Admin">A flag representing whether the module is an Admin module</param>
        /// <returns>The Module Definition Id of the new Module</returns>
        /// <history>
        /// [cnurse]	10/14/2004	documented
        /// [cnurse]    11/11/2004  removed addition of Module Control (now in AddMOduleControl)
        /// </history>
        /// -----------------------------------------------------------------------------
        private static int AddModuleDefinition(string DesktopModuleName, string Description, string ModuleDefinitionName, bool Premium, bool Admin)
        {
            return AddModuleDefinition(DesktopModuleName, Description, ModuleDefinitionName, Premium, Admin, Null.NullString, Null.NullString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleDefinition adds a new Core Module Definition to the system
        /// </summary>
        /// <remarks>
        /// This overload allows the caller to determine whether the module has a controller
        /// class
        /// </remarks>
        /// <param name="DesktopModuleName">The Friendly Name of the Module to Add</param>
        /// <param name="Description">Description of the Module</param>
        /// <param name="ModuleDefinitionName">The Module Definition Name</param>
        /// <param name="Premium">A flag representing whether the module is a Premium module</param>
        /// <param name="Admin">A flag representing whether the module is an Admin module</param>
        /// <param name="Controller">The Controller Class string</param>
        /// <returns>The Module Definition Id of the new Module</returns>
        /// <history>
        /// [cnurse]	10/14/2004	documented
        /// [cnurse]    11/11/2004  removed addition of Module Control (now in AddMOduleControl)
        /// </history>
        /// -----------------------------------------------------------------------------
        private static int AddModuleDefinition(string DesktopModuleName, string Description, string ModuleDefinitionName, bool Premium, bool Admin, string Controller)
        {
            return AddModuleDefinition(DesktopModuleName, Description, ModuleDefinitionName, Premium, Admin, Controller, Null.NullString);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleDefinition adds a new Core Module Definition to the system
        /// </summary>
        /// <remarks>
        /// This overload allows the caller to determine whether the module has a controller
        /// class
        /// </remarks>
        /// <param name="DesktopModuleName">The Friendly Name of the Module to Add</param>
        /// <param name="Description">Description of the Module</param>
        /// <param name="ModuleDefinitionName">The Module Definition Name</param>
        /// <param name="Premium">A flag representing whether the module is a Premium module</param>
        /// <param name="Admin">A flag representing whether the module is an Admin module</param>
        /// <param name="Controller">The Controller Class string</param>
        /// <param name="Version">The Module Version</param>
        /// <returns>The Module Definition Id of the new Module</returns>
        /// <history>
        /// [cnurse]	10/14/2004	documented
        /// [cnurse]    11/11/2004  removed addition of Module Control (now in AddMOduleControl)
        /// </history>
        /// -----------------------------------------------------------------------------
        private static int AddModuleDefinition(string DesktopModuleName, string Description, string ModuleDefinitionName, bool Premium, bool Admin, string Controller, string Version)
        {
            DesktopModuleController objDesktopModules = new DesktopModuleController();
            DesktopModuleInfo objDesktopModule = objDesktopModules.GetDesktopModuleByName(DesktopModuleName);
            if (objDesktopModule == null)
            {
                objDesktopModule = new DesktopModuleInfo();
                objDesktopModule.DesktopModuleID = Null.NullInteger;
                objDesktopModule.FriendlyName = DesktopModuleName;
                objDesktopModule.FolderName = DesktopModuleName;
                objDesktopModule.ModuleName = DesktopModuleName;
                objDesktopModule.Description = Description;
                objDesktopModule.Version = Version;
                objDesktopModule.IsPremium = Premium;
                objDesktopModule.IsAdmin = Admin;
                objDesktopModule.BusinessControllerClass = Controller;
                objDesktopModule.DesktopModuleID = objDesktopModules.AddDesktopModule(objDesktopModule);
            }
            ModuleDefinitionController objModuleDefinitions = new ModuleDefinitionController();
            ModuleDefinitionInfo objModuleDefinition = objModuleDefinitions.GetModuleDefinitionByName(objDesktopModule.DesktopModuleID, ModuleDefinitionName);
            if (objModuleDefinition == null)
            {
                objModuleDefinition = new ModuleDefinitionInfo();
                objModuleDefinition.ModuleDefID = Null.NullInteger;
                objModuleDefinition.DesktopModuleID = objDesktopModule.DesktopModuleID;
                objModuleDefinition.FriendlyName = ModuleDefinitionName;
                objModuleDefinition.ModuleDefID = objModuleDefinitions.AddModuleDefinition(objModuleDefinition);
            }
            return objModuleDefinition.ModuleDefID;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleToPage adds a module to a Page
        /// </summary>
        /// <remarks>
        /// This overload assumes ModulePermissions will be inherited
        /// </remarks>
        /// <param name="page">The Page to add the Module to</param>
        /// <param name="ModuleDefId">The Module Deinition Id for the module to be aded to this tab</param>
        /// <param name="ModuleTitle">The Module's title</param>
        /// <param name="ModuleIconFile">The Module's icon</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddModuleToPage(DotNetNuke.Entities.Tabs.TabInfo page, int ModuleDefId, string ModuleTitle, string ModuleIconFile)
        {
            AddModuleToPage(page, ModuleDefId, ModuleTitle, ModuleIconFile, true);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddModuleToPage adds a module to a Page
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="page">The Page to add the Module to</param>
        /// <param name="ModuleDefId">The Module Deinition Id for the module to be aded to this tab</param>
        /// <param name="ModuleTitle">The Module's title</param>
        /// <param name="ModuleIconFile">The Module's icon</param>
        /// <param name="InheritPermissions">Inherit the Pages View Permisions</param>
        /// <history>
        /// [cnurse]	11/16/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddModuleToPage(DotNetNuke.Entities.Tabs.TabInfo page, int ModuleDefId, string ModuleTitle, string ModuleIconFile, bool InheritPermissions)
        {
            ModuleController objModules = new ModuleController();
            ModuleInfo objModule = new ModuleInfo();
            bool blnDuplicate = false;
            ArrayList arrModules = objModules.GetPortalTabModules(page.PortalID, page.TabID);
            int refIntHelperL0 = arrModules.Count - 1;
            for (int intIndex = 0; intIndex <= refIntHelperL0; intIndex++)
            {
                objModule = (ModuleInfo) arrModules[intIndex];
                if (objModule.ModuleDefID == ModuleDefId)
                {
                    blnDuplicate = true;
                }
            }
            if (!blnDuplicate)
            {
                objModule = new ModuleInfo();
                objModule.ModuleID = Null.NullInteger;
                objModule.PortalID = page.PortalID;
                objModule.TabID = page.TabID;
                objModule.ModuleOrder = -1;
                objModule.ModuleTitle = ModuleTitle;
                objModule.PaneName = "ContentPane";
                objModule.ModuleDefID = ModuleDefId;
                objModule.CacheTime = 0;
                objModule.IconFile = ModuleIconFile;
                objModule.AllTabs = false;
                objModule.Visibility = VisibilityState.Maximized;
                objModule.InheritViewPermissions = InheritPermissions;
                try
                {
                    objModules.AddModule(objModule);
                }
                catch (Exception exception1)
                {
                    
                    
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddPage adds a Tab Page
        /// </summary>
        /// <remarks>
        /// Adds a Tab to a parentTab
        /// </remarks>
        /// <param name="parentTab">The Parent Tab</param>
        /// <param name="TabName">The Name to give this new Tab</param>
        /// <param name="TabIconFile">The Icon for this new Tab</param>
        /// <param name="IsVisible">A flag indicating whether the tab is visible</param>
        /// <param name="permissions">Page Permissions Collection for this page</param>
        /// <param name="IsAdmin">Is an admin page</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static DotNetNuke.Entities.Tabs.TabInfo AddPage(DotNetNuke.Entities.Tabs.TabInfo parentTab, string TabName, string TabIconFile, bool IsVisible, TabPermissionCollection permissions, bool IsAdmin)
        {
            int ParentId = Null.NullInteger;
            int PortalId = Null.NullInteger;
            if (parentTab != null)
            {
                ParentId = parentTab.TabID;
                PortalId = parentTab.PortalID;
            }
            return AddPage(PortalId, ParentId, TabName, TabIconFile, IsVisible, permissions, IsAdmin);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddPage adds a Tab Page
        /// </summary>
        /// <param name="PortalId">The Id of the Portal</param>
        /// <param name="ParentId">The Id of the Parent Tab</param>
        /// <param name="TabName">The Name to give this new Tab</param>
        /// <param name="TabIconFile">The Icon for this new Tab</param>
        /// <param name="IsVisible">A flag indicating whether the tab is visible</param>
        /// <param name="permissions">Page Permissions Collection for this page</param>
        /// <param name="IsAdmin">Is and admin page</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static DotNetNuke.Entities.Tabs.TabInfo AddPage(int PortalId, int ParentId, string TabName, string TabIconFile, bool IsVisible, TabPermissionCollection permissions, bool IsAdmin)
        {
            TabController objTabs = new TabController();
            DotNetNuke.Entities.Tabs.TabInfo objTab = objTabs.GetTabByName(TabName, PortalId, ParentId);
            if (objTab == null)
            {
                objTab = new DotNetNuke.Entities.Tabs.TabInfo();
                objTab.TabID = Null.NullInteger;
                objTab.PortalID = PortalId;
                objTab.TabName = TabName;
                objTab.Title = "";
                objTab.Description = "";
                objTab.KeyWords = "";
                objTab.IsVisible = IsVisible;
                objTab.DisableLink = false;
                objTab.ParentId = ParentId;
                objTab.IconFile = TabIconFile;
                objTab.AdministratorRoles = Null.NullString;
                objTab.IsDeleted = false;
                objTab.TabPermissions = permissions;
                objTab.TabID = objTabs.AddTab(objTab, !IsAdmin);
            }
            return objTab;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddPagePermission adds a TabPermission to a TabPermission Collection
        /// </summary>
        /// <param name="permissions">Page Permissions Collection for this page</param>
        /// <param name="key">The Permission key</param>
        /// <param name="roleId">The role given the permission</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddPagePermission(ref TabPermissionCollection permissions, string key, int roleId)
        {
            PermissionController objPermissionController = new PermissionController();
            PermissionInfo objPermission = (PermissionInfo) objPermissionController.GetPermissionByCodeAndKey("SYSTEM_TAB", key)[0];
            TabPermissionInfo objTabPermission = new TabPermissionInfo();
            objTabPermission.PermissionID = objPermission.PermissionID;
            objTabPermission.RoleID = roleId;
            objTabPermission.AllowAccess = true;
            permissions.Add(objTabPermission);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddPortal manages the Installation of a new DotNetNuke Portal
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse]	11/06/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static int AddPortal(XmlNode node, bool status, int indent)
        {
            int AddPortal;
            try
            {
                string strHostPath = DotNetNuke.Common.Globals.HostMapPath;
                string strChildPath = "";
                string strDomain = "";
                if (HttpContext.Current != null)
                {
                    strDomain = DotNetNuke.Common.Globals.GetDomainName(HttpContext.Current.Request).Replace("/Install", "");
                }
                string strPortalName = XmlUtils.GetNodeValue(node, "portalname", "");
                if (status)
                {
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Creating Portal: " + strPortalName + "<br>");
                }
                PortalController objPortalController = new PortalController();
                PortalSecurity objSecurity = new PortalSecurity();
                XmlNode adminNode = node.SelectSingleNode("administrator");
                string strFirstName = XmlUtils.GetNodeValue(adminNode, "firstname", "");
                string strLastName = XmlUtils.GetNodeValue(adminNode, "lastname", "");
                string strUserName = XmlUtils.GetNodeValue(adminNode, "username", "");
                string strPassword = XmlUtils.GetNodeValue(adminNode, "password", "");
                string strEmail = XmlUtils.GetNodeValue(adminNode, "email", "");
                string strDescription = XmlUtils.GetNodeValue(node, "description", "");
                string strKeyWords = XmlUtils.GetNodeValue(node, "keywords", "");
                string strTemplate = XmlUtils.GetNodeValue(node, "templatefile", "");
                string strServerPath = DotNetNuke.Common.Globals.ApplicationMapPath + @"\";
                bool isChild = bool.Parse(XmlUtils.GetNodeValue(node, "ischild", ""));
                string strHomeDirectory = XmlUtils.GetNodeValue(node, "homedirectory", "");
                XmlNodeList portalAliases = node.SelectNodes("portalaliases/portalalias");
                string strPortalAlias = strDomain;
                if ((portalAliases.Count > 0) && (portalAliases[0].InnerText != ""))
                {
                    strPortalAlias = portalAliases[0].InnerText;
                }
                if (strEmail == "")
                {
                    strEmail = "admin@" + strDomain.Replace("www.", "");
                    if (strEmail.IndexOf("/") != -1)
                    {
                        strEmail = strEmail.Substring(0, strEmail.IndexOf("/"));
                    }
                }
                if (isChild)
                {
                    strChildPath = Strings.Mid(strPortalAlias, Strings.InStrRev(strPortalAlias, "/", -1, CompareMethod.Binary) + 1);
                }
                int intPortalId = objPortalController.CreatePortal(strPortalName, strFirstName, strLastName, strUserName, objSecurity.Encrypt(Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["EncryptionKey"])), strPassword), strEmail, strDescription, strKeyWords, strHostPath, strTemplate, strHomeDirectory, strPortalAlias, strServerPath, strServerPath + strChildPath, isChild);
                if (intPortalId > -1)
                {
                    IEnumerator refObjectHelperL0=null;
                    try
                    {
                        refObjectHelperL0 = portalAliases.GetEnumerator();
                        while (refObjectHelperL0.MoveNext())
                        {
                            XmlNode portalAlias = (XmlNode) refObjectHelperL0.Current;
                            if (portalAlias.InnerText != "")
                            {
                                if (status)
                                {
                                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Creating Portal Alias: " + portalAlias.InnerText + "<br>");
                                }
                                objPortalController.AddPortalAlias(intPortalId, portalAlias.InnerText);
                            }
                        }
                    }
                    finally
                    {
                        if (refObjectHelperL0 is IDisposable)
                        {
                            (refObjectHelperL0 as IDisposable).Dispose();
                        }
                    }
                }
                AddPortal = intPortalId;
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Error: " + ex.Message + "<br>");
                AddPortal = -1;
                
                return AddPortal;
                
            }
            return AddPortal;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// AddSearchResults adds a top level Hidden Search Results Page
        /// </summary>
        /// <param name="ModuleDefId">The Module Deinition Id for the Search Results Module</param>
        /// <history>
        /// [cnurse]	11/11/2004	created 
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void AddSearchResults(int ModuleDefId)
        {
            ArrayList arrPortals = new PortalController().GetPortals();
            int refIntHelperL0 = arrPortals.Count - 1;
            for (int intPortal = 0; intPortal <= refIntHelperL0; intPortal++)
            {
                TabPermissionCollection objTabPermissions = new TabPermissionCollection();
                PortalInfo objPortal = (PortalInfo) arrPortals[intPortal];
                AddPagePermission(ref objTabPermissions, "View", Convert.ToInt32("-1"));
                AddPagePermission(ref objTabPermissions, "View", Convert.ToInt32(objPortal.AdministratorRoleId));
                AddPagePermission(ref objTabPermissions, "Edit", Convert.ToInt32(objPortal.AdministratorRoleId));
                AddModuleToPage(AddPage(objPortal.PortalID, Null.NullInteger, "Search Results", "", false, objTabPermissions, false), ModuleDefId, "Search Results", "");
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ConvertLegacyUsers converts legacy Users to the new ASP.NET MemberRole Provider (v3.0)
        /// </summary>
        /// <remarks>
        /// Used in Upgrading from v2.1.2 to v3.0.x
        /// </remarks>
        /// <param name="dr">DataReader containing the legacy Users</param>
        /// <history>
        /// [cnurse]	11/6/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static ArrayList ConvertLegacyUsers(IDataReader dr)
        {
            ArrayList ConvertLegacyUsers;
            ArrayList arrUsers = new ArrayList();
            int iCount = 0;
            int iMin = 1;
            try
            {
                while (dr.Read())
                {
                    if ((iCount % 0x3e8) == 0)
                    {
                        HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Building User Array - Adding Users: " + iMin.ToString() + "<br>");
                        iCount++;
                        iMin += 0x3e8;
                    }
                    UserInfo objSuperUserInfo = new UserInfo();
                    try
                    {
                        objSuperUserInfo.UserID = Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["UserID"]));
                    }
                    catch (Exception exception1)
                    {
                        
                        
                    }
                    try
                    {
                        objSuperUserInfo.PortalID = Convert.ToInt32(RuntimeHelpers.GetObjectValue(dr["PortalID"]));
                    }
                    catch (Exception exception2)
                    {
                        ProjectData.SetProjectError(exception2);
                        
                    }
                    try
                    {
                        objSuperUserInfo.IsSuperUser = Convert.ToBoolean(RuntimeHelpers.GetObjectValue(dr["IsSuperUser"]));
                    }
                    catch (Exception exception3)
                    {
                        ProjectData.SetProjectError(exception3);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Membership.Username = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Username"]));
                    }
                    catch (Exception exception4)
                    {
                        ProjectData.SetProjectError(exception4);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Membership.Approved = Convert.ToBoolean(RuntimeHelpers.GetObjectValue(dr["Authorized"]));
                    }
                    catch (Exception exception5)
                    {
                        ProjectData.SetProjectError(exception5);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Membership.CreatedDate = Convert.ToDateTime(RuntimeHelpers.GetObjectValue(dr["CreatedDate"]));
                    }
                    catch (Exception exception6)
                    {
                        ProjectData.SetProjectError(exception6);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Membership.Email = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Email"]));
                    }
                    catch (Exception exception7)
                    {
                        ProjectData.SetProjectError(exception7);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.FirstName = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["FirstName"]));
                    }
                    catch (Exception exception8)
                    {
                        ProjectData.SetProjectError(exception8);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.LastName = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["LastName"]));
                    }
                    catch (Exception exception9)
                    {
                        ProjectData.SetProjectError(exception9);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Membership.Password = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Password"]));
                    }
                    catch (Exception exception10)
                    {
                        ProjectData.SetProjectError(exception10);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.City = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["City"]));
                    }
                    catch (Exception exception11)
                    {
                        ProjectData.SetProjectError(exception11);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.Country = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Country"]));
                    }
                    catch (Exception exception12)
                    {
                        ProjectData.SetProjectError(exception12);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.PostalCode = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["PostalCode"]));
                    }
                    catch (Exception exception13)
                    {
                        ProjectData.SetProjectError(exception13);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.Region = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Region"]));
                    }
                    catch (Exception exception14)
                    {
                        ProjectData.SetProjectError(exception14);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.Street = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Street"]));
                    }
                    catch (Exception exception15)
                    {
                        ProjectData.SetProjectError(exception15);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.Telephone = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Telephone"]));
                    }
                    catch (Exception exception16)
                    {
                        ProjectData.SetProjectError(exception16);
                        
                    }
                    try
                    {
                        objSuperUserInfo.Profile.Unit = Convert.ToString(RuntimeHelpers.GetObjectValue(dr["Unit"]));
                    }
                    catch (Exception exception17)
                    {
                        ProjectData.SetProjectError(exception17);
                        
                    }
                    arrUsers.Add(objSuperUserInfo);
                }
                ConvertLegacyUsers = arrUsers;
            }
            finally
            {
                if (dr != null)
                {
                    dr.Close();
                }
            }
            return ConvertLegacyUsers;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// CoreModuleExists determines whether a Core Module exists on the system
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="DesktopModuleName">The Friendly Name of the Module</param>
        /// <returns>True if the Module exists, otherwise False</returns>
        /// <history>
        /// [cnurse]	10/14/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static bool CoreModuleExists(string DesktopModuleName)
        {
            DesktopModuleController objDesktopModules = new DesktopModuleController();
            return (objDesktopModules.GetDesktopModuleByName(DesktopModuleName) != null);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// DeleteFiles - clean up deprecated files and folders
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strVersion">The Version being Upgraded</param>
        /// <history>
        /// [swalker]	11/09/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static string DeleteFiles(string strVersion)
        {
            string strExceptions = "";
            try
            {
                IEnumerator refObjectHelperL0=null;
                string strListFile = DotNetNuke.Common.Globals.HostMapPath + strVersion + ".txt";
                if (!File.Exists(strListFile))
                {
                    return strExceptions;
                }
                StreamReader objStreamReader = File.OpenText(strListFile);
                Array arrPaths = objStreamReader.ReadToEnd().Split("\r\n".ToCharArray());
                objStreamReader.Close();
                try
                {
                    refObjectHelperL0 = arrPaths.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        string strPath = Conversions.ToString(refObjectHelperL0.Current);
                        if (strPath.Trim() != "")
                        {
                            strPath = HttpContext.Current.Server.MapPath(@"..\" + strPath);
                            if (strPath.EndsWith(@"\"))
                            {
                                if (Directory.Exists(strPath))
                                {
                                    try
                                    {
                                        DotNetNuke.Common.Globals.DeleteFolderRecursive(strPath);
                                    }
                                    catch (Exception exception1)
                                    {
                                        
                                        Exception ex = exception1;
                                        strExceptions = strExceptions + "Error: " + ex.Message + "\r\n";
                                        
                                    }
                                }
                            }
                            else if (File.Exists(strPath))
                            {
                                try
                                {
                                    File.SetAttributes(strPath, FileAttributes.Normal);
                                    File.Delete(strPath);
                                }
                                catch (Exception exception2)
                                {
                                    ProjectData.SetProjectError(exception2);
                                    Exception ex = exception2;
                                    strExceptions = strExceptions + "Error: " + ex.Message + "\r\n";
                                    
                                }
                            }
                        }
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
            }
            catch (Exception exception3)
            {
                ProjectData.SetProjectError(exception3);
                Exception ex = exception3;
                strExceptions = strExceptions + "Error: " + ex.Message + "\r\n";
                
            }
            return strExceptions;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ExecuteScript executes a SQl script file
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="script">The script to Execute</param>
        /// <param name="version">The script version</param>
        /// <history>
        /// [cnurse]	11/09/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static string ExecuteScript(string script, string version)
        {
            ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data");
            string strScriptFile = script;
            StreamReader objStreamReader = File.OpenText(strScriptFile);
            string strScript = objStreamReader.ReadToEnd();
            objStreamReader.Close();
            string strExceptions = PortalSettings.ExecuteScript(strScript);
            if (version != "")
            {
                strExceptions = strExceptions + UpgradeApplication(version) + DeleteFiles(version);
            }
            try
            {
                StreamWriter objStream = File.CreateText(strScriptFile.Replace("." + objProviderConfiguration.DefaultProvider, "") + ".log");
                objStream.WriteLine(strExceptions);
                objStream.Close();
            }
            catch (Exception exception1)
            {
                
                
            }
            return strExceptions;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ExecuteScripts manages the Execution of Scripts from the Install/Scripts folder.
        /// It is also triggered by InstallDNN and UpgradeDNN
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strProviderPath">The path to the Data Provider</param>
        /// <history>
        /// [cnurse]	05/04/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void ExecuteScripts(string strProviderPath)
        {
            ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data");
            string ScriptPath = DotNetNuke.Common.Globals.ApplicationMapPath + @"\Install\Scripts\";
            if (Directory.Exists(ScriptPath))
            {
                foreach (string strFile in Directory.GetFiles(ScriptPath))
                {
                    if (strFile.IndexOf("." + objProviderConfiguration.DefaultProvider) != -1)
                    {
                        HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing Script: " + strFile + "<br>");
                        ExecuteScript(strFile, "");
                        try
                        {
                            File.SetAttributes(strFile, FileAttributes.Normal);
                            File.Delete(strFile);
                        }
                        catch (Exception exception1)
                        {
                            
                            
                        }
                    }
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// GetModuleDefinition gets the Module Definition Id of a module
        /// </summary>
        /// <param name="DesktopModuleName">The Friendly Name of the Module to Add</param>
        /// <param name="ModuleDefinitionName">The Module Definition Name</param>
        /// <returns>The Module Definition Id of the Module (-1 if no module definition)</returns>
        /// <history>
        /// [cnurse]	11/16/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static int GetModuleDefinition(string DesktopModuleName, string ModuleDefinitionName)
        {
            DesktopModuleInfo objDesktopModule = new DesktopModuleController().GetDesktopModuleByName(DesktopModuleName);
            if (objDesktopModule == null)
            {
                return -1;
            }
            ModuleDefinitionInfo objModuleDefinition = new ModuleDefinitionController().GetModuleDefinitionByName(objDesktopModule.DesktopModuleID, ModuleDefinitionName);
            if (objModuleDefinition == null)
            {
                return -1;
            }
            return objModuleDefinition.ModuleDefID;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// HostTabExists determines whether a tab of a given name exists under the Host tab
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="TabName">The Name of the Tab</param>
        /// <returns>True if the Tab exists, otherwise False</returns>
        /// <history>
        /// [cnurse]	11/08/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static bool HostTabExists(string TabName)
        {
            TabController objTabController = new TabController();
            return (objTabController.GetTabByName(TabName, Null.NullInteger) != null);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// InstallDNN manages the Installation of a new DotNetNuke Application
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strProviderPath">The path to the Data Provider</param>
        /// <history>
        /// [cnurse]	11/06/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void InstallDNN(string strProviderPath)
        {
            string strExceptions = "";
            string strHostPath = DotNetNuke.Common.Globals.HostMapPath;
            XmlDocument xmlDoc = new XmlDocument();
            string strVersion = "";
            string strScript = "";
            string strErrorMessage = "";
            string strAssemblyVersion = "04.00.00".Replace(".", "");
            string installTemplate = Config.GetSetting("InstallTemplate");
            try
            {
                xmlDoc.Load(DotNetNuke.Common.Globals.ApplicationMapPath + @"\Install\" + installTemplate);
            }
            catch (Exception exception1)
            {
                
                strErrorMessage = strErrorMessage + "Failed to load Install template.<br><br>";
                
            }
            if (strErrorMessage == "")
            {
                IEnumerator refObjectHelperL1=null;
                XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke");
                if (node != null)
                {
                    strVersion = XmlUtils.GetNodeValue(node, "version", "");
                }
                Array arrVersion = strVersion.Split(new char[] { '.' });
                int intMajor = Conversions.ToInteger(arrVersion.GetValue(0));
                int intMinor = Conversions.ToInteger(arrVersion.GetValue(1));
                int intBuild = Conversions.ToInteger(arrVersion.GetValue(2));
                DotNetNuke.Modules.Admin.ResourceInstaller.ResourceInstaller objResourceInstaller = new DotNetNuke.Modules.Admin.ResourceInstaller.ResourceInstaller();
                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Version: " + intMajor.ToString() + "." + intMinor.ToString() + "." + intBuild.ToString() + "<br>");
                node = xmlDoc.SelectSingleNode("//dotnetnuke/scripts");
                if (node != null)
                {
                    IEnumerator refObjectHelperL0=null;
                    ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data");
                    try
                    {
                        refObjectHelperL0 = node.SelectNodes("script").GetEnumerator();
                        while (refObjectHelperL0.MoveNext())
                        {
                            XmlNode scriptNode = (XmlNode) refObjectHelperL0.Current;
                            strScript = scriptNode.InnerText + "." + objProviderConfiguration.DefaultProvider;
                            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Script: " + strScript + "<br>");
                            strExceptions = strExceptions + ExecuteScript(strProviderPath + strScript, "");
                        }
                    }
                    finally
                    {
                        if (refObjectHelperL0 is IDisposable)
                        {
                            (refObjectHelperL0 as IDisposable).Dispose();
                        }
                    }
                }
                bool installMemberRole = true;
                if (Config.GetSetting("InstallMemberRole") != null)
                {
                    installMemberRole = bool.Parse(Config.GetSetting("InstallMemberRole"));
                }
                if (installMemberRole)
                {
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing MemberRole Provider:<br>");
                    strExceptions = strExceptions + InstallMemberRoleProvider(strProviderPath);
                }
                PortalSettings.UpdateDatabaseVersion(intMajor, intMinor, intBuild);
                UpgradeDNN(strProviderPath, strVersion.Replace(".", ""));
                node = xmlDoc.SelectSingleNode("//dotnetnuke/settings");
                if (node != null)
                {
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Settings:<br>");
                    ParseSettings(node);
                }
                node = xmlDoc.SelectSingleNode("//dotnetnuke/superuser");
                if (node != null)
                {
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Configuring SuperUser:<br>");
                    ParseSuperUser(node);
                }
                node = xmlDoc.SelectSingleNode("//dotnetnuke/desktopmodules");
                if (node != null)
                {
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Desktop Modules:<br>");
                    ParseDesktopModules(node);
                }
                node = xmlDoc.SelectSingleNode("//dotnetnuke/files");
                if (node != null)
                {
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Files:<br>");
                    ParseFiles(node, Null.NullInteger);
                }
                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Modules:<br>");
                objResourceInstaller.Install(true, 2, "modules");
                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing Additional Scripts:<br>");
                ExecuteScripts(strProviderPath);
                XmlNodeList nodes = xmlDoc.SelectNodes("//dotnetnuke/portals/portal");
                try
                {
                    refObjectHelperL1 = nodes.GetEnumerator();
                    while (refObjectHelperL1.MoveNext())
                    {
                        node = (XmlNode) refObjectHelperL1.Current;
                        if (node != null)
                        {
                            int intPortalId = AddPortal(node, true, 2);
                            if (intPortalId > -1)
                            {
                                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Successfully Installed Portal " + Conversions.ToString(intPortalId) + ":<br>");
                            }
                            else
                            {
                                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Portal failed to install:<br>");
                            }
                        }
                    }
                }
                finally
                {
                    if (refObjectHelperL1 is IDisposable)
                    {
                        (refObjectHelperL1 as IDisposable).Dispose();
                    }
                }
                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Optional Resources:<br>");
                objResourceInstaller.Install(true, 2);
            }
            else
            {
                StreamReader objStreamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/500.htm"));
                string strHTML = objStreamReader.ReadToEnd();
                objStreamReader.Close();
                strHTML = Strings.Replace(strHTML, "[MESSAGE]", strErrorMessage, 1, -1, CompareMethod.Binary);
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Response.Write(strHTML);
                    HttpContext.Current.Response.End();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// InstallMemberRoleProvider - Installs the MemberRole Provider Db objects
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strProviderPath">The Path to the Provider Directory</param>
        /// <history>
        /// [cnurse]	02/02/2005	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static string InstallMemberRoleProvider(string strProviderPath)
        {
            string strExceptions = "";
            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing InstallCommon.sql<br>");
            StreamReader objStreamReader = File.OpenText(strProviderPath + "InstallCommon.sql");
            string strScript = objStreamReader.ReadToEnd();
            objStreamReader.Close();
            strExceptions = strExceptions + PortalSettings.ExecuteScript(strScript);
            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing InstallMembership.sql<br>");
            objStreamReader = File.OpenText(strProviderPath + "InstallMembership.sql");
            strScript = objStreamReader.ReadToEnd();
            objStreamReader.Close();
            strExceptions = strExceptions + PortalSettings.ExecuteScript(strScript);
            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing InstallProfile.sql<br>");
            objStreamReader = File.OpenText(strProviderPath + "InstallProfile.sql");
            strScript = objStreamReader.ReadToEnd();
            objStreamReader.Close();
            strExceptions = strExceptions + PortalSettings.ExecuteScript(strScript);
            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing InstallRoles.sql<br>");
            objStreamReader = File.OpenText(strProviderPath + "InstallRoles.sql");
            strScript = objStreamReader.ReadToEnd();
            objStreamReader.Close();
            strExceptions = strExceptions + PortalSettings.ExecuteScript(strScript);
            upgradeMemberShipProvider = false;
            return strExceptions;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ParseDesktopModules parses the Host Template's Desktop Modules node
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="node">The Desktop Modules node</param>
        /// <history>
        /// [cnurse]	11/08/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void ParseDesktopModules(XmlNode node)
        {
            IEnumerator refObjectHelperL0=null;
            try
            {
                refObjectHelperL0 = node.SelectNodes("desktopmodule").GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    IEnumerator refObjectHelperL1=null;
                    XmlNode desktopModuleNode = (XmlNode) refObjectHelperL0.Current;
                    string strDescription = XmlUtils.GetNodeValue(desktopModuleNode, "description", "");
                    string strVersion = XmlUtils.GetNodeValue(desktopModuleNode, "version", "");
                    string strControllerClass = XmlUtils.GetNodeValue(desktopModuleNode, "businesscontrollerclass", "");
                    try
                    {
                        refObjectHelperL1 = desktopModuleNode.SelectNodes("modules/module").GetEnumerator();
                        while (refObjectHelperL1.MoveNext())
                        {
                            IEnumerator refObjectHelperL2=null;
                            XmlNode moduleNode = (XmlNode) refObjectHelperL1.Current;
                            string strName = XmlUtils.GetNodeValue(moduleNode, "friendlyname", "");
                            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Installing " + strName + ":<br>");
                            int ModuleDefID = AddModuleDefinition(strName, strDescription, strName, false, false, strControllerClass, strVersion);
                            try
                            {
                                refObjectHelperL2 = moduleNode.SelectNodes("controls/control").GetEnumerator();
                                while (refObjectHelperL2.MoveNext())
                                {
                                    SecurityAccessLevel controlType=SecurityAccessLevel.View;
                                    XmlNode controlNode = (XmlNode) refObjectHelperL2.Current;
                                    string strKey = XmlUtils.GetNodeValue(controlNode, "key", "");
                                    string strTitle = XmlUtils.GetNodeValue(controlNode, "title", "");
                                    string strSrc = XmlUtils.GetNodeValue(controlNode, "src", "");
                                    string strIcon = XmlUtils.GetNodeValue(controlNode, "iconfile", "");
                                    string strType = XmlUtils.GetNodeValue(controlNode, "type", "");
                                    switch (XmlUtils.GetNodeValue(controlNode, "type", ""))
                                    {
                                        case "View":
                                            controlType = SecurityAccessLevel.View;
                                            break;

                                        case "Edit":
                                            controlType = SecurityAccessLevel.Edit;
                                            break;
                                    }
                                    string strHelpUrl = XmlUtils.GetNodeValue(controlNode, "helpurl", "");
                                    AddModuleControl(ModuleDefID, strKey, strTitle, strSrc, strIcon, controlType, 0, strHelpUrl);
                                }
                            }
                            finally
                            {
                                if (refObjectHelperL2 is IDisposable)
                                {
                                    (refObjectHelperL2 as IDisposable).Dispose();
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (refObjectHelperL1 is IDisposable)
                        {
                            (refObjectHelperL1 as IDisposable).Dispose();
                        }
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ParseFiles parses the Host Template's Files node
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="node">The Files node</param>
        /// <param name="portalId">The PortalId (-1 for Host Files)</param>
        /// <history>
        /// [cnurse]	11/08/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void ParseFiles(XmlNode node, int portalId)
        {
            IEnumerator refObjectHelperL0=null;
            FileController objController = new FileController();
            try
            {
                refObjectHelperL0 = node.SelectNodes("file").GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    XmlNode fileNode = (XmlNode) refObjectHelperL0.Current;
                    string strFileName = XmlUtils.GetNodeValue(fileNode, "filename", "");
                    string strExtenstion = XmlUtils.GetNodeValue(fileNode, "extension", "");
                    long fileSize = long.Parse(XmlUtils.GetNodeValue(fileNode, "size", ""));
                    int iWidth = XmlUtils.GetNodeValueInt(fileNode, "width", 0);
                    int iHeight = XmlUtils.GetNodeValueInt(fileNode, "height", 0);
                    string strType = XmlUtils.GetNodeValue(fileNode, "contentType", "");
                    string strFolder = XmlUtils.GetNodeValue(fileNode, "folder", "");
                    objController.AddFile(portalId, strFileName, strExtenstion, fileSize, iWidth, iHeight, strType, strFolder);
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ParseSettings parses the Host Template's Settings node
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="node">The settings node</param>
        /// <history>
        /// [cnurse]	11/08/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void ParseSettings(XmlNode node)
        {
            IEnumerator refObjectHelperL0=null;
            HostSettingsController objController = new HostSettingsController();
            try
            {
                refObjectHelperL0 = node.ChildNodes.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    XmlNode settingNode = (XmlNode) refObjectHelperL0.Current;
                    string strSettingName = settingNode.Name;
                    string strSettingValue = settingNode.InnerText;
                    XmlAttribute SecureAttrib = settingNode.Attributes["Secure"];
                    bool SettingIsSecure = false;
                    if ((SecureAttrib != null) && (SecureAttrib.Value.ToLower() == "true"))
                    {
                        SettingIsSecure = true;
                    }
                    string strDomainName = DotNetNuke.Common.Globals.GetDomainName(HttpContext.Current.Request);
                    string refStringHelperL0 = strSettingName;
                    if (refStringHelperL0 == "HostURL")
                    {
                        if (strSettingValue == "")
                        {
                            strSettingValue = strDomainName;
                        }
                    }
                    else if ((refStringHelperL0 == "HostEmail") && (strSettingValue == ""))
                    {
                        strSettingValue = "support@" + strDomainName;
                        strSettingValue = strSettingValue.Substring(0, strSettingValue.IndexOf("/"));
                    }
                    objController.UpdateHostSetting(strSettingName, strSettingValue, SettingIsSecure);
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
            DataCache.RemoveCache("GetHostSettings");
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// ParseSuperUser parses the Host Template's SuperUser node
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="node">The SuperUser node</param>
        /// <history>
        /// [cnurse]	11/08/2004	created
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void ParseSuperUser(XmlNode node)
        {
            UserController objUser = new UserController();
            string strFirstName = XmlUtils.GetNodeValue(node, "firstname", "");
            string strLastName = XmlUtils.GetNodeValue(node, "lastname", "");
            string strUserName = XmlUtils.GetNodeValue(node, "username", "");
            string strPassword = XmlUtils.GetNodeValue(node, "password", "");
            string strEmail = XmlUtils.GetNodeValue(node, "email", "");
            string strLocale = XmlUtils.GetNodeValue(node, "locale", "");
            int timeZone = XmlUtils.GetNodeValueInt(node, "timezone", 0);
            UserInfo objSuperUserInfo = new UserInfo();
            objSuperUserInfo.PortalID = -1;
            objSuperUserInfo.Profile.FirstName = strFirstName;
            objSuperUserInfo.Profile.LastName = strLastName;
            objSuperUserInfo.Membership.Username = strUserName;
            objSuperUserInfo.Membership.Password = strPassword;
            objSuperUserInfo.Membership.Email = strEmail;
            objSuperUserInfo.IsSuperUser = true;
            objSuperUserInfo.Membership.Approved = true;
            objSuperUserInfo.Profile.PreferredLocale = strLocale;
            objSuperUserInfo.Profile.TimeZone = timeZone;
            int HostId = objUser.AddUser(objSuperUserInfo);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RemoveCoreModule removes a Core Module from the system
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="DesktopModuleName">The Friendly Name of the Module to Remove</param>
        /// <param name="ParentTabName">The Name of the parent Tab/Page for this module</param>
        /// <param name="TabName">The Name to tab that contains the Module</param>
        /// <param name="TabRemove">A flag to determine whether to remove the Tab if it has no
        /// other modules</param>
        /// <history>
        /// [cnurse]	10/14/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void RemoveCoreModule(string DesktopModuleName, string ParentTabName, string TabName, bool TabRemove)
        {
            int intIndex=0;
            int intModuleDefId=0;
            TabController objTabs = new TabController();
            ModuleController objModules = new ModuleController();
            ModuleInfo objModule = new ModuleInfo();
            string refStringHelperL0 = ParentTabName;
            if ((refStringHelperL0 != "Host") && (refStringHelperL0 == "Admin"))
            {
                ArrayList arrPortals = new PortalController().GetPortals();
                int refIntHelperL0 = arrPortals.Count - 1;
                for (int intPortal = 0; intPortal <= refIntHelperL0; intPortal++)
                {
                    PortalInfo objPortal = (PortalInfo) arrPortals[intPortal];
                    int ParentId = objPortal.AdminTabId;
                    DotNetNuke.Entities.Tabs.TabInfo objTab = objTabs.GetTabByName(TabName, objPortal.PortalID, ParentId);
                    ArrayList arrModules = objModules.GetPortalTabModules(objPortal.PortalID, objTab.TabID);
                    int intCount = arrModules.Count;
                    int refIntHelperL1 = arrModules.Count - 1;
                    intIndex = 0;
                    while (intIndex <= refIntHelperL1)
                    {
                        objModule = (ModuleInfo) arrModules[intIndex];
                        if (objModule.FriendlyName == DesktopModuleName)
                        {
                            objModules.DeleteModule(objModule.ModuleID);
                            intModuleDefId = objModule.ModuleDefID;
                            intCount--;
                        }
                        intIndex++;
                    }
                    if ((intCount == 0) & TabRemove)
                    {
                        objTabs.DeleteTab(objTab.TabID, objTab.PortalID);
                    }
                }
            }
            ModuleControlController objModuleControls = new ModuleControlController();
            ArrayList arrModuleControls = objModuleControls.GetModuleControls(intModuleDefId);
            int refIntHelperL2 = arrModuleControls.Count - 1;
            for (intIndex = 0; intIndex <= refIntHelperL2; intIndex++)
            {
                ModuleControlInfo objModuleControl = (ModuleControlInfo) arrModuleControls[intIndex];
                objModuleControls.DeleteModuleControl(objModuleControl.ModuleControlID);
            }
            ModuleDefinitionController objModuleDefinitions = new ModuleDefinitionController();
            int intDesktopModuleId = objModuleDefinitions.GetModuleDefinition(intModuleDefId).DesktopModuleID;
            objModuleDefinitions.DeleteModuleDefinition(intModuleDefId);
            new DesktopModuleController().DeleteDesktopModule(intDesktopModuleId);
        }

        public static void StartTimer()
        {
            startTime = DateAndTime.Now;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// TransferUsersToMembershipProvider transfers legacy users to the
        /// new ASP.NET MemberRole Architecture
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="PortalID">Id of the Portal</param>
        /// <history>
        /// [cnurse]	11/6/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void TransferUsersToMembershipProvider(int PortalID)
        {
            ArrayList arrUsers = ConvertLegacyUsers(DataProvider.Instance().GetUsers(PortalID));
            TransferUsersToMembershipProvider(PortalID, arrUsers, false);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// TransferUsersToMembershipProvider transfers legacy users to the
        /// new ASP.NET MemberRole Architecture
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="PortalID">Id of the Portal</param>
        /// <param name="arrUsers">An ArrayList of the Users</param>
        /// <param name="SuperUsers">A flag indicating whether the users are SuperUsers</param>
        /// <history>
        /// [cnurse]	11/6/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static void TransferUsersToMembershipProvider(int PortalID, ArrayList arrUsers, bool SuperUsers)
        {
            UserController objUserCont = new UserController();
            try
            {
                if (SuperUsers)
                {
                    DotNetNuke.Common.Globals.SetApplicationName(-1);
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Start Transferring SuperUsers to MemberRole:<br>");
                }
                else
                {
                    DotNetNuke.Common.Globals.SetApplicationName(PortalID);
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Start Transferring Portal Users to MemberRole: PortalId= " + PortalID.ToString() + "<br>");
                }
                string EncryptionKey = "";
                IDataReader dr = DataProvider.Instance().GetHostSetting("EncryptionKey");
                if (dr.Read())
                {
                    EncryptionKey = dr["SettingValue"].ToString();
                }
                dr.Close();
                int iMin = 1;
                int iMax = 100;
                int refIntHelperL0 = arrUsers.Count - 1;
                for (int i = 0; i <= refIntHelperL0; i++)
                {
                    MembershipCreateStatus objStatus;
                    if ((i % 100) == 0)
                    {
                        if (iMin > arrUsers.Count)
                        {
                            iMin = arrUsers.Count;
                        }
                        if (iMax > arrUsers.Count)
                        {
                            iMax = arrUsers.Count;
                        }
                        HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Transferring Users:" + iMin.ToString() + " to " + iMax.ToString() + "<br>");
                        iMin += 100;
                        iMax += 100;
                    }
                    UserInfo objUser = (UserInfo) arrUsers[i];
                    string strPassword = new PortalSecurity().Decrypt(EncryptionKey, objUser.Membership.Password);
                    if (objUser.IsSuperUser)
                    {
                        objUser.Membership.Approved = true;
                    }
                    MembershipUser objMembershipUser = Membership.CreateUser(objUser.Membership.Username, strPassword, objUser.Membership.Email, null, null, objUser.Membership.Approved, out objStatus);
                    if (objStatus != MembershipCreateStatus.Success)
                    {
                        DotNetNuke.Services.Exceptions.Exceptions.LogException(new Exception(objStatus.ToString()));
                    }
                    else
                    {
                        try
                        {
                            ProfileBase objProfile = ProfileBase.Create(objUser.Membership.Username, true);
                            objProfile["FirstName"] = objUser.Profile.FirstName;
                            objProfile["LastName"] = objUser.Profile.LastName;
                            objProfile["Unit"] = objUser.Profile.Unit;
                            objProfile["Street"] = objUser.Profile.Street;
                            objProfile["City"] = objUser.Profile.City;
                            objProfile["Region"] = objUser.Profile.Region;
                            objProfile["PostalCode"] = objUser.Profile.PostalCode;
                            objProfile["Country"] = objUser.Profile.Country;
                            objProfile["Telephone"] = objUser.Profile.Telephone;
                            objProfile.Save();
                        }
                        catch (Exception exception1)
                        {
                            
                            Exception exc = exception1;
                            DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
                            
                        }
                        string[] arrUserRoles = new RoleController().GetPortalRolesByUser(objUser.UserID, PortalID);
                        if (arrUserRoles != null)
                        {
                            try
                            {
                                Roles.AddUserToRoles(objUser.Membership.Username, arrUserRoles);
                            }
                            catch (Exception exception2)
                            {
                                ProjectData.SetProjectError(exception2);
                                Exception exc = exception2;
                                DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
                                
                            }
                        }
                    }
                }
            }
            finally
            {
                DotNetNuke.Common.Globals.SetApplicationName(PortalID);
            }
            if (SuperUsers)
            {
                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Finish Transferring SuperUsers to MemberRole:<br>");
            }
            else
            {
                DotNetNuke.Common.Globals.SetApplicationName(PortalID);
                HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Finish Transferring Portal Users to MemberRole: PortalId= " + PortalID.ToString() + "<br>");
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// UpgradeApplication - This overload is used for general application upgrade operations. 
        /// </summary>
        /// <remarks>
        /// Since it is not version specific and is invoked whenever the application is 
        /// restarted, the operations must be re-executable.
        /// </remarks>
        /// <history>
        /// [cnurse]	11/6/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static string UpgradeApplication()
        {
            string strExceptions = "";
            DotNetNuke.Entities.Tabs.TabInfo HostPage = new TabController().GetTabByName("Host", Null.NullInteger);
            try
            {
                int ModuleDefID;
                IEnumerator refObjectHelperL0=null;
                if (CoreModuleExists("System Messages"))
                {
                    RemoveCoreModule("System Messages", "Admin", "Site Settings", false);
                }
                if (!CoreModuleExists("Log Viewer"))
                {
                    ModuleDefID = AddModuleDefinition("Log Viewer", "Allows you to view log entries for portal events.", "Log Viewer");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Logging/LogViewer.ascx", "", SecurityAccessLevel.Admin, 0);
                    AddModuleControl(ModuleDefID, "Edit", "Edit Log Settings", "Admin/Logging/EditLogTypes.ascx", "", SecurityAccessLevel.Host, 0);
                    AddAdminPages("Log Viewer", "icon_viewstats_16px.gif", true, ModuleDefID, "Log Viewer", "icon_viewstats_16px.gif");
                }
                if (!CoreModuleExists("Authentication"))
                {
                    ModuleDefID = AddModuleDefinition("Windows Authentication", "Allows you to manage authentication settings for sites using Windows Authentication.", "Windows Authentication");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Security/AuthenticationSettings.ascx", "", SecurityAccessLevel.Admin, 0);
                    AddAdminPages("Authentication", "icon_authentication_16px.gif", true, ModuleDefID, "Authentication", "icon_authentication_16px.gif");
                }
                if (!CoreModuleExists("Schedule"))
                {
                    ModuleDefID = AddModuleDefinition("Schedule", "Allows you to schedule tasks to be run at specified intervals.", "Schedule");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Scheduling/ViewSchedule.ascx", "", SecurityAccessLevel.Admin, 0);
                    AddModuleControl(ModuleDefID, "Edit", "Edit Schedule", "Admin/Scheduling/EditSchedule.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "History", "Schedule History", "Admin/Scheduling/ViewScheduleHistory.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "Status", "Schedule Status", "Admin/Scheduling/ViewScheduleStatus.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleToPage(AddHostPage("Schedule", "icon_scheduler_16px.gif", true), ModuleDefID, "Schedule", "icon_scheduler_16px.gif");
                }
                if (!CoreModuleExists("Skins"))
                {
                    ModuleDefID = AddModuleDefinition("Skins", "Allows you to manage your skins and containers.", "Skins");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Skins/EditSkins.ascx", "", SecurityAccessLevel.Admin, 0);
                    AddAdminPages("Skins", "icon_skins_16px.gif", true, ModuleDefID, "Skins", "icon_skins_16px.gif");
                }
                if (!CoreModuleExists("Template"))
                {
                    ModuleDefID = AddModuleDefinition("Template", "Allows you to export a portal template to be used to build new portals.", "Export Template");
                    AddModuleControl(ModuleDefID, "", "Export Template", "Admin/Portal/Template.ascx", "", SecurityAccessLevel.Host, 1);
                    AddModuleToPage(AddHostPage("Portals", "", true), ModuleDefID, "Export Template", "");
                }
                if (!CoreModuleExists("Languages"))
                {
                    ModuleDefID = AddModuleDefinition("Languages", "The Super User can manage the suported languages installed on the system.", "Languages");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Localization/Languages.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "TimeZone", "TimeZone Editor", "Admin/Localization/TimeZoneEditor.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "Language", "Language Editor", "Admin/Localization/LanguageEditor.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "FullEditor", "Language Editor", "Admin/Localization/LanguageEditorExt.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "Verify", "Resource File Verifier", "Admin/Localization/ResourceVerifier.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "Package", "Create Language Pack", "Admin/Localization/LanguagePack.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleToPage(AddHostPage("Languages", "icon_language_16px.gif", true), ModuleDefID, "Languages", "icon_language_16px.gif");
                    ModuleDefID = AddModuleDefinition("Custom Locales", "Administrator can manage custom translations for portal.", "Custom Portal Locale");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Localization/LanguageEditor.ascx", "", SecurityAccessLevel.Admin, 0);
                    AddModuleControl(ModuleDefID, "FullEditor", "Language Editor", "Admin/Localization/LanguageEditorExt.ascx", "", SecurityAccessLevel.Admin, 0);
                    AddAdminPages("Languages", "icon_language_16px.gif", true, ModuleDefID, "Languages", "icon_language_16px.gif");
                }
                if (!CoreModuleExists("Search Admin"))
                {
                    ModuleDefID = AddModuleDefinition("Search Admin", "The Search Admininstrator provides the ability to manage search settings.", "Search Admin");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Search/SearchAdmin.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleToPage(AddHostPage("Search Admin", "icon_search_16px.gif", true), ModuleDefID, "Search Admin", "icon_search_16px.gif");
                }
                if (!CoreModuleExists("Search Input"))
                {
                    ModuleDefID = AddModuleDefinition("Search Input", "The Search Input module provides the ability to submit a search to a given search results module.", "Search Input", false, false);
                    AddModuleControl(ModuleDefID, "", "", "DesktopModules/SearchInput/SearchInput.ascx", "", SecurityAccessLevel.Anonymous, 0);
                    AddModuleControl(ModuleDefID, "Settings", "Search Input Settings", "DesktopModules/SearchInput/Settings.ascx", "", SecurityAccessLevel.Edit, 0);
                }
                if (!CoreModuleExists("Search Results"))
                {
                    ModuleDefID = AddModuleDefinition("Search Results", "The Search Reasults module provides the ability to display search results.", "Search Results", false, false);
                    AddModuleControl(ModuleDefID, "", "", "DesktopModules/SearchResults/SearchResults.ascx", "", SecurityAccessLevel.Anonymous, 0);
                    AddModuleControl(ModuleDefID, "Settings", "Search Results Settings", "DesktopModules/SearchResults/Settings.ascx", "", SecurityAccessLevel.Edit, 0);
                    AddSearchResults(ModuleDefID);
                }
                if (!CoreModuleExists("Site Wizard"))
                {
                    ModuleDefID = AddModuleDefinition("Site Wizard", "The Administrator can use this user-friendly wizard to set up the common features of the Portal/Site.", "Site Wizard");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Portal/Sitewizard.ascx", "", SecurityAccessLevel.Admin, 0);
                    AddAdminPages("Site Wizard", "icon_sitesettings_16px.gif", false, ModuleDefID, "Site Wizard", "icon_sitesettings_16px.gif");
                }
                if (!CoreModuleExists("Portal Aliases"))
                {
                    ModuleDefID = AddModuleDefinition("Portal Aliases", "Allows you to view portal aliases.", "Portal Aliases");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Portal/PortalAlias.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleControl(ModuleDefID, "Edit", "Portal Aliases", "Admin/Portal/EditPortalAlias.ascx", "", SecurityAccessLevel.Host, 0);
                    AddAdminPages("Site Settings", "icon_sitesettings_16px.gif", false, ModuleDefID, "Portal Aliases", "icon_sitesettings_16px.gif", false);
                }
                if (!HostTabExists("Lists"))
                {
                    ModuleDefID = AddModuleDefinition("Lists", "Allows you to edit common lists.", "Lists");
                    AddModuleControl(ModuleDefID, "", "", "Admin/Lists/ListEditor.ascx", "", SecurityAccessLevel.Host, 0);
                    AddModuleToPage(AddHostPage("Lists", "icon_lists_16px.gif", true), ModuleDefID, "Lists", "icon_lists_16px.gif");
                }
                if (CoreModuleExists("Feedback"))
                {
                    AddModuleControl(GetModuleDefinition("Feedback", "Feedback"), "Settings", "Feedback Settings", "DesktopModules/Feedback/Settings.ascx", "", SecurityAccessLevel.Edit, 0);
                }
                if (!HostTabExists("Superuser Accounts"))
                {
                    DesktopModuleInfo objDesktopModuleInfo = new DesktopModuleController().GetDesktopModuleByName("User Accounts");
                    ModuleDefinitionController objModuleDefController = new ModuleDefinitionController();
                    ModuleDefID = objModuleDefController.GetModuleDefinitionByName(objDesktopModuleInfo.DesktopModuleID, "User Accounts").ModuleDefID;
                    AddModuleToPage(AddHostPage("Superuser Accounts", "icon_users_16px.gif", true), ModuleDefID, "Superuser Accounts", "icon_users_32px.gif");
                }
                if (!HostTabExists("Skins"))
                {
                    DesktopModuleInfo objDesktopModuleInfo = new DesktopModuleController().GetDesktopModuleByName("Skins");
                    ModuleDefinitionController objModuleDefController = new ModuleDefinitionController();
                    ModuleDefID = objModuleDefController.GetModuleDefinitionByName(objDesktopModuleInfo.DesktopModuleID, "Skins").ModuleDefID;
                    AddModuleToPage(AddHostPage("Skins", "icon_skins_16px.gif", true), ModuleDefID, "Skins", "");
                }
                AddModuleControl(Null.NullInteger, "SEARCH", Null.NullString, "Admin/Skins/Search.ascx", "", SecurityAccessLevel.SkinObject, Null.NullInteger);
                AddModuleControl(Null.NullInteger, "TREEVIEW", Null.NullString, "Admin/Skins/TreeViewMenu.ascx", "", SecurityAccessLevel.SkinObject, Null.NullInteger);
                AddModuleControl(GetModuleDefinition("Module Definitions", "Module Definitions"), "Package", "Create Private Assembly", "Admin/ModuleDefinitions/PrivateAssembly.ascx", "icon_moduledefinitions_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger);
                ArrayList arrAliases = new PortalAliasController().GetPortalAliasArrayByPortalID(Null.NullInteger);
                try
                {
                    refObjectHelperL0 = arrAliases.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        PortalAliasInfo objAlias = (PortalAliasInfo) refObjectHelperL0.Current;
                        if (objAlias.HTTPAlias.LastIndexOf("/") != -1)
                        {
                            string childPath = DotNetNuke.Common.Globals.ApplicationMapPath + @"\" + objAlias.HTTPAlias.Substring(objAlias.HTTPAlias.LastIndexOf("/") + 1);
                            if (Directory.Exists(childPath))
                            {
                                File.Copy(childPath + @"\Default.aspx", childPath + @"\old_Default.aspx", true);
                                File.Copy(DotNetNuke.Common.Globals.HostMapPath + "subhost.aspx", childPath + @"\Default.aspx", true);
                            }
                        }
                    }
                    return strExceptions;
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
            }
            catch (Exception exception1)
            {
                
                Exception ex = exception1;
                strExceptions = strExceptions + "Error: " + ex.Message + "\r\n";
                try
                {
                    DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                }
                catch (Exception exception2)
                {
                    ProjectData.SetProjectError(exception2);
                    
                }
                
            }
            return strExceptions;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// UpgradeApplication - This overload is used for version specific application upgrade operations. 
        /// </summary>
        /// <remarks>
        /// This should be used for file system modifications or upgrade operations which 
        /// should only happen once. Database references are not recommended because future 
        /// versions of the application may result in code incompatibilties.
        /// </remarks>
        /// <param name="Version">The Version being Upgraded</param>
        /// <history>
        /// [cnurse]	11/6/2004	documented
        /// </history>
        /// -----------------------------------------------------------------------------
        private static string UpgradeApplication(string Version)
        {
            string strExceptions = "";
            try
            {
                IEnumerator refObjectHelperL0=null;
                IEnumerator refObjectHelperL1=null;
                string refStringHelperL0 = Version;
                switch (refStringHelperL0)
                {
                    case "02.00.00":
                    {
                        string strServerPath = HttpContext.Current.Request.MapPath(DotNetNuke.Common.Globals.ApplicationPath);
                        string strPortalsDirMapPath = DotNetNuke.Common.Globals.ApplicationMapPath + "/Portals/";
                        IDataReader dr = DataProvider.Instance().GetPortals();
                        while (dr.Read())
                        {
                            if (Directory.Exists(strPortalsDirMapPath + dr["GUID"].ToString()))
                            {
                                if (Directory.Exists(strPortalsDirMapPath + dr["PortalID"].ToString()))
                                {
                                    try
                                    {
                                        Directory.Move(strPortalsDirMapPath + dr["PortalID"].ToString(), strServerPath + @"\Portals\" + dr["PortalID"].ToString() + "_old");
                                    }
                                    catch (Exception exception1)
                                    {
                                        
                                        Exception ex = exception1;
                                        strExceptions = strExceptions + "Could Not Move Folder " + strPortalsDirMapPath + dr["GUID"].ToString() + " To " + strPortalsDirMapPath + dr["PortalID"].ToString() + ". Error: " + ex.Message + "\r\n";
                                        
                                    }
                                }
                                try
                                {
                                    Directory.Move(strPortalsDirMapPath + dr["GUID"].ToString(), strPortalsDirMapPath + dr["PortalID"].ToString());
                                }
                                catch (Exception exception2)
                                {
                                    ProjectData.SetProjectError(exception2);
                                    Exception ex = exception2;
                                    strExceptions = strExceptions + "Could Not Move Folder " + strPortalsDirMapPath + dr["GUID"].ToString() + " To " + strPortalsDirMapPath + dr["PortalID"].ToString() + ". Error: " + ex.Message + "\r\n";
                                    
                                }
                            }
                        }
                        dr.Close();
                        if (!File.Exists(strPortalsDirMapPath + @"0\portal.css") && File.Exists(DotNetNuke.Common.Globals.HostMapPath + "portal.css"))
                        {
                            File.Copy(DotNetNuke.Common.Globals.HostMapPath + "portal.css", strPortalsDirMapPath + @"0\portal.css");
                        }
                        return strExceptions;
                    }
                    case "02.02.00":
                    {
                        int ModCount;
                        string strProviderPath = PortalSettings.GetProviderPath();
                        if (strProviderPath.StartsWith("ERROR:"))
                        {
                            return (strExceptions + strProviderPath);
                        }
                        bool installMemberRole = true;
                        if (Config.GetSetting("InstallMemberRole") != null)
                        {
                            installMemberRole = bool.Parse(Config.GetSetting("InstallMemberRole"));
                        }
                        if (installMemberRole)
                        {
                            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing MemberRole Provider:<br>");
                            strExceptions = strExceptions + InstallMemberRoleProvider(strProviderPath);
                        }
                        ArrayList arrPortals = new PortalController().GetPortals();
                        string OriginalApplicationName = DotNetNuke.Common.Globals.GetApplicationName();
                        PermissionController objPermissionController = new PermissionController();
                        PermissionInfo objPermission = new PermissionInfo();
                        objPermission.PermissionCode = "SYSTEM_MODULE_DEFINITION";
                        objPermission.PermissionKey = "VIEW";
                        objPermission.PermissionName = "View";
                        objPermission.ModuleDefID = Null.NullInteger;
                        int intViewModulePermissionID = objPermissionController.AddPermission(objPermission);
                        objPermission.PermissionKey = "EDIT";
                        objPermission.PermissionName = "Edit";
                        int intEditModulePermissionID = objPermissionController.AddPermission(objPermission);
                        objPermission.PermissionCode = "SYSTEM_TAB";
                        objPermission.PermissionKey = "VIEW";
                        objPermission.PermissionName = "View Tab";
                        int intViewTabPermissionID = objPermissionController.AddPermission(objPermission);
                        objPermission.PermissionKey = "EDIT";
                        objPermission.PermissionName = "Edit Tab";
                        int intEditTabPermissionID = objPermissionController.AddPermission(objPermission);
                        objPermission.PermissionCode = "SYSTEM_FOLDER";
                        objPermission.PermissionKey = "READ";
                        objPermission.PermissionName = "View Folder";
                        int intReadFolderPermissionID = objPermissionController.AddPermission(objPermission);
                        objPermission.PermissionKey = "WRITE";
                        objPermission.PermissionName = "Write to Folder";
                        int intWriteFolderPermissionID = objPermissionController.AddPermission(objPermission);
                        FolderController objFolderController = new FolderController();
                        FolderPermissionController objFolderPermissionController = new FolderPermissionController();
                        int refIntHelperL0 = arrPortals.Count - 1;
                        for (int PortalCount = 0; PortalCount <= refIntHelperL0; PortalCount++)
                        {
                            PortalInfo objPortal = (PortalInfo) arrPortals[PortalCount];
                            int FolderID = objFolderController.AddFolder(objPortal.PortalID, "");
                            FolderPermissionInfo objFolderPermission = new FolderPermissionInfo();
                            objFolderPermission.FolderID = FolderID;
                            objFolderPermission.PermissionID = intReadFolderPermissionID;
                            objFolderPermission.AllowAccess = true;
                            objFolderPermission.RoleID = objPortal.AdministratorRoleId;
                            objFolderPermissionController.AddFolderPermission(objFolderPermission);
                            objFolderPermission.PermissionID = intWriteFolderPermissionID;
                            objFolderPermissionController.AddFolderPermission(objFolderPermission);
                        }
                        ArrayList arrSuperUsers = new ArrayList();
                        UserController objUserController = new UserController();
                        arrSuperUsers = ConvertLegacyUsers(DataProvider.Instance().GetSuperUsers());
                        TransferUsersToMembershipProvider(-1, arrSuperUsers, true);
                        int refIntHelperL1 = arrPortals.Count - 1;
                        for (int j = 0; j <= refIntHelperL1; j++)
                        {
                            PortalInfo objPortal = (PortalInfo) arrPortals[j];
                            DotNetNuke.Common.Globals.SetApplicationName(objPortal.PortalID);
                            ArrayList arrRoles = new RoleController().GetPortalRoles(objPortal.PortalID);
                            int refIntHelperL2 = arrRoles.Count - 1;
                            for (int q = 0; q <= refIntHelperL2; q++)
                            {
                                try
                                {
                                    Roles.CreateRole(((RoleInfo) arrRoles[q]).RoleName);
                                }
                                catch (Exception exception3)
                                {
                                    ProjectData.SetProjectError(exception3);
                                    Exception exc = exception3;
                                    DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
                                    
                                }
                            }
                            TransferUsersToMembershipProvider(objPortal.PortalID);
                        }
                        DotNetNuke.Common.Globals.SetApplicationName(OriginalApplicationName);
                        ArrayList arrModuleDefinitions = new ModuleDefinitionController().GetModuleDefinitions(Null.NullInteger);
                        ArrayList arrModules = new ModuleController().GetAllModules();
                        ModulePermissionController objModulePermissionController = new ModulePermissionController();
                        int refIntHelperL3 = arrModules.Count - 1;
                        for (ModCount = 0; ModCount <= refIntHelperL3; ModCount++)
                        {
                            int k;
                            string[] roles;
                            ModuleInfo objModule = (ModuleInfo) arrModules[ModCount];
                            ModulePermissionInfo objModulePermission = new ModulePermissionInfo();
                            objModulePermission.ModuleID = objModule.ModuleID;
                            if (objModule.AuthorizedViewRoles.IndexOf(";") > 0)
                            {
                                roles = Strings.Split(objModule.AuthorizedViewRoles, ";", -1, CompareMethod.Binary);
                                int refIntHelperL4 = roles.Length - 1;
                                k = 0;
                                while (k <= refIntHelperL4)
                                {
                                    if (Versioned.IsNumeric(roles[k]))
                                    {
                                        objModulePermission.PermissionID = intViewModulePermissionID;
                                        objModulePermission.AllowAccess = true;
                                        objModulePermission.RoleID = Convert.ToInt32(roles[k]);
                                        objModulePermissionController.AddModulePermission(objModulePermission);
                                    }
                                    k++;
                                }
                            }
                            if (objModule.AuthorizedEditRoles.IndexOf(";") > 0)
                            {
                                roles = Strings.Split(objModule.AuthorizedEditRoles, ";", -1, CompareMethod.Binary);
                                int refIntHelperL5 = roles.Length - 1;
                                for (k = 0; k <= refIntHelperL5; k++)
                                {
                                    if (Versioned.IsNumeric(roles[k]))
                                    {
                                        objModulePermission.PermissionID = intEditModulePermissionID;
                                        objModulePermission.AllowAccess = true;
                                        objModulePermission.RoleID = Convert.ToInt32(roles[k]);
                                        objModulePermissionController.AddModulePermission(objModulePermission);
                                    }
                                }
                            }
                        }
                        ArrayList arrTabs = new TabController().GetAllTabs();
                        TabPermissionController objTabPermissionController = new TabPermissionController();
                        int refIntHelperL6 = arrTabs.Count - 1;
                        for (ModCount = 0; ModCount <= refIntHelperL6; ModCount++)
                        {
                            int k;
                            string[] roles;
                            DotNetNuke.Entities.Tabs.TabInfo objTab = (DotNetNuke.Entities.Tabs.TabInfo) arrTabs[ModCount];
                            TabPermissionInfo objTabPermission = new TabPermissionInfo();
                            objTabPermission.TabID = objTab.TabID;
                            if (objTab.AuthorizedRoles.IndexOf(";") > 0)
                            {
                                roles = Strings.Split(objTab.AuthorizedRoles, ";", -1, CompareMethod.Binary);
                                int refIntHelperL7 = roles.Length - 1;
                                k = 0;
                                while (k <= refIntHelperL7)
                                {
                                    if (Versioned.IsNumeric(roles[k]))
                                    {
                                        objTabPermission.PermissionID = intViewTabPermissionID;
                                        objTabPermission.AllowAccess = true;
                                        objTabPermission.RoleID = Convert.ToInt32(roles[k]);
                                        objTabPermissionController.AddTabPermission(objTabPermission);
                                    }
                                    k++;
                                }
                            }
                            if (objTab.AdministratorRoles.IndexOf(";") > 0)
                            {
                                roles = Strings.Split(objTab.AdministratorRoles, ";", -1, CompareMethod.Binary);
                                int refIntHelperL8 = roles.Length - 1;
                                for (k = 0; k <= refIntHelperL8; k++)
                                {
                                    if (Versioned.IsNumeric(roles[k]))
                                    {
                                        objTabPermission.PermissionID = intEditTabPermissionID;
                                        objTabPermission.AllowAccess = true;
                                        objTabPermission.RoleID = Convert.ToInt32(roles[k]);
                                        objTabPermissionController.AddTabPermission(objTabPermission);
                                    }
                                }
                            }
                        }
                        return strExceptions;
                    }
                    case "03.00.01":
                    {
                        ArrayList arrTabs = new TabController().GetAllTabs();
                        int refIntHelperL9 = arrTabs.Count - 1;
                        for (int TabCount = 0; TabCount <= refIntHelperL9; TabCount++)
                        {
                            DotNetNuke.Entities.Tabs.TabInfo objTab = (DotNetNuke.Entities.Tabs.TabInfo) arrTabs[TabCount];
                            if (objTab != null)
                            {
                                objTab.TabPath = DotNetNuke.Common.Globals.GenerateTabPath(objTab.ParentId, objTab.TabName);
                                DataProvider.Instance().UpdateTab(objTab.TabID, objTab.TabName, objTab.IsVisible, objTab.DisableLink, objTab.ParentId, objTab.IconFile, objTab.Title, objTab.Description, objTab.KeyWords, objTab.IsDeleted, objTab.Url, objTab.SkinSrc, objTab.ContainerSrc, objTab.TabPath, objTab.StartDate, objTab.EndDate);
                            }
                        }
                        return strExceptions;
                    }
                    case "03.00.06":
                        DataCache.RemoveCache("GetHostSettings");
                        return strExceptions;

                    case "03.00.11":
                    {
                        PersonalizationController objPersonalizationController = new PersonalizationController();
                        IDataReader dr = DataProvider.Instance().GetAllProfiles();
                        while (dr.Read())
                        {
                            PersonalizationInfo objPersonalization = new PersonalizationInfo();
                            try
                            {
                                objPersonalization.UserId = Convert.ToInt32(RuntimeHelpers.GetObjectValue(Null.SetNull(RuntimeHelpers.GetObjectValue(dr["UserID"]), objPersonalization.UserId)));
                            }
                            catch (Exception exception4)
                            {
                                ProjectData.SetProjectError(exception4);
                                
                            }
                            try
                            {
                                objPersonalization.PortalId = Convert.ToInt32(RuntimeHelpers.GetObjectValue(Null.SetNull(RuntimeHelpers.GetObjectValue(dr["PortalId"]), objPersonalization.PortalId)));
                            }
                            catch (Exception exception5)
                            {
                                ProjectData.SetProjectError(exception5);
                                
                            }
                            objPersonalization.Profile = DotNetNuke.Common.Globals.DeserializeHashTableBase64(dr["ProfileData"].ToString());
                            objPersonalization.IsModified = true;
                            objPersonalizationController.SaveProfile(objPersonalization);
                        }
                        dr.Close();
                        return strExceptions;
                    }
                    case "03.00.12":
                        if (upgradeMemberShipProvider)
                        {
                            string strProviderPath = PortalSettings.GetProviderPath();
                            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing UpgradeMembershipProvider.sql<br>");
                            StreamReader objStreamReader = File.OpenText(strProviderPath + "UpgradeMembershipProvider.sql");
                            string strScript = objStreamReader.ReadToEnd();
                            objStreamReader.Close();
                            strExceptions = strExceptions + PortalSettings.ExecuteScript(strScript);
                        }
                        return strExceptions;
                }
                if (refStringHelperL0 != "03.01.00")
                {
                    return strExceptions;
                }
                LogController objLogController = new LogController();
                XmlDocument xmlDoc = new XmlDocument();
                string xmlConfigFile = DotNetNuke.Common.Globals.HostMapPath + @"Logs\LogConfig\LogConfig.xml.resources";
                try
                {
                    xmlDoc.Load(xmlConfigFile);
                }
                catch (FileNotFoundException exception6)
                {
                    ProjectData.SetProjectError(exception6);
                    FileNotFoundException exc = exception6;
                    xmlConfigFile = DotNetNuke.Common.Globals.HostMapPath + @"Logs\LogConfig\LogConfigTemplate.xml.resources";
                    xmlDoc.Load(xmlConfigFile);
                    
                }
                XmlNodeList LogType = xmlDoc.SelectNodes("/LogConfig/LogTypes/LogType");
                try
                {
                    refObjectHelperL0 = LogType.GetEnumerator();
                    while (refObjectHelperL0.MoveNext())
                    {
                        XmlNode LogTypeInfo = (XmlNode) refObjectHelperL0.Current;
                        LogTypeInfo objLogTypeInfo = new LogTypeInfo();
                        objLogTypeInfo.LogTypeKey = LogTypeInfo.Attributes["LogTypeKey"].Value;
                        objLogTypeInfo.LogTypeFriendlyName = LogTypeInfo.Attributes["LogTypeFriendlyName"].Value;
                        objLogTypeInfo.LogTypeDescription = LogTypeInfo.Attributes["LogTypeDescription"].Value;
                        objLogTypeInfo.LogTypeCSSClass = LogTypeInfo.Attributes["LogTypeCSSClass"].Value;
                        objLogTypeInfo.LogTypeOwner = LogTypeInfo.Attributes["LogTypeOwner"].Value;
                        objLogController.AddLogType(objLogTypeInfo);
                    }
                }
                finally
                {
                    if (refObjectHelperL0 is IDisposable)
                    {
                        (refObjectHelperL0 as IDisposable).Dispose();
                    }
                }
                XmlNodeList LogTypeConfig = xmlDoc.SelectNodes("/LogConfig/LogTypeConfig");
                try
                {
                    refObjectHelperL1 = LogTypeConfig.GetEnumerator();
                    while (refObjectHelperL1.MoveNext())
                    {
                        XmlNode LogTypeConfigInfo = (XmlNode) refObjectHelperL1.Current;
                        LogTypeConfigInfo objLogTypeConfig = new LogTypeConfigInfo();
                        objLogTypeConfig.EmailNotificationIsActive = Convert.ToBoolean(RuntimeHelpers.GetObjectValue(Interaction.IIf(LogTypeConfigInfo.Attributes["EmailNotificationStatus"].Value == "On", true, false)));
                        objLogTypeConfig.KeepMostRecent = LogTypeConfigInfo.Attributes["KeepMostRecent"].Value;
                        objLogTypeConfig.LoggingIsActive = Convert.ToBoolean(RuntimeHelpers.GetObjectValue(Interaction.IIf(LogTypeConfigInfo.Attributes["LoggingStatus"].Value == "On", true, false)));
                        objLogTypeConfig.LogTypeKey = LogTypeConfigInfo.Attributes["LogTypeKey"].Value;
                        objLogTypeConfig.LogTypePortalID = LogTypeConfigInfo.Attributes["LogTypePortalID"].Value;
                        objLogTypeConfig.MailFromAddress = LogTypeConfigInfo.Attributes["MailFromAddress"].Value;
                        objLogTypeConfig.MailToAddress = LogTypeConfigInfo.Attributes["MailToAddress"].Value;
                        objLogTypeConfig.NotificationThreshold = Convert.ToInt32(LogTypeConfigInfo.Attributes["NotificationThreshold"].Value);
                        objLogTypeConfig.NotificationThresholdTime = Convert.ToInt32(LogTypeConfigInfo.Attributes["NotificationThresholdTime"].Value);
                        objLogTypeConfig.NotificationThresholdTimeType = (LogTypeConfigInfo.NotificationThresholdTimeTypes) Conversions.ToInteger(LogTypeConfigInfo.Attributes["NotificationThresholdTimeType"].Value);
                        objLogController.AddLogTypeConfigInfo(objLogTypeConfig);
                    }
                }
                finally
                {
                    if (refObjectHelperL1 is IDisposable)
                    {
                        (refObjectHelperL1 as IDisposable).Dispose();
                    }
                }
                ScheduleItem objScheduleItem = new ScheduleItem();
                objScheduleItem.TypeFullName = "DotNetNuke.Services.Cache.PurgeCache, DOTNETNUKE";
                objScheduleItem.AttachToEvent = "";
                objScheduleItem.CatchUpEnabled = false;
                if (DotNetNuke.Common.Globals.WebFarmEnabled)
                {
                    objScheduleItem.Enabled = true;
                }
                else
                {
                    objScheduleItem.Enabled = false;
                }
                objScheduleItem.ObjectDependencies = "";
                objScheduleItem.RetainHistoryNum = 10;
                objScheduleItem.Servers = "";
                objScheduleItem.TimeLapse = 2;
                objScheduleItem.TimeLapseMeasurement = "h";
                objScheduleItem.RetryTimeLapse = 30;
                objScheduleItem.RetryTimeLapseMeasurement = "m";
                SchedulingProvider.Instance().AddSchedule(objScheduleItem);
            }
            catch (Exception exception7)
            {
                ProjectData.SetProjectError(exception7);
                Exception ex = exception7;
                strExceptions = strExceptions + "Error: " + ex.Message + "\r\n";
                try
                {
                    DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
                }
                catch (Exception exception8)
                {
                    ProjectData.SetProjectError(exception8);
                    
                }
                
            }
            return strExceptions;
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// UpgradeDNN manages the Upgrade of an exisiting DotNetNuke Application
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="strProviderPath">The path to the Data Provider</param>
        /// <param name="strDatabaseVersion">The current Database Version</param>
        /// <history>
        /// [cnurse]	11/06/2004	created (Upgrade code extracted from AutoUpgrade)
        /// [cnurse]    11/10/2004  version specific upgrades extracted to ExecuteScript
        /// [cnurse]    01/20/2005  changed to Public so Upgrade can be manually controlled
        /// </history>
        /// -----------------------------------------------------------------------------
        public static void UpgradeDNN(string strProviderPath, string strDatabaseVersion)
        {
            string strExceptions;
            string strScriptVersion;
            bool useConfig;
            IEnumerator refObjectHelperL0=null;
            string strAssemblyVersion = "04.00.00".Replace(".", "");
            ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data");
            ArrayList arrScriptFiles = new ArrayList();
            foreach (string strFile in Directory.GetFiles(strProviderPath, "*." + objProviderConfiguration.DefaultProvider))
            {
                if (Strings.Len(Path.GetFileName(strFile)) == (9 + Strings.Len(objProviderConfiguration.DefaultProvider)))
                {
                    strScriptVersion = Path.GetFileNameWithoutExtension(strFile);
                    if ((Microsoft.VisualBasic.CompilerServices.Operators.CompareString(strScriptVersion.Replace(".", ""), strDatabaseVersion, false) > 0) & (Microsoft.VisualBasic.CompilerServices.Operators.CompareString(strScriptVersion.Replace(".", ""), strAssemblyVersion, false) <= 0))
                    {
                        arrScriptFiles.Add(strFile);
                    }
                }
            }
            arrScriptFiles.Sort();
            try
            {
                refObjectHelperL0 = arrScriptFiles.GetEnumerator();
                while (refObjectHelperL0.MoveNext())
                {
                    string strScriptFile = Conversions.ToString(refObjectHelperL0.Current);
                    strScriptVersion = Path.GetFileNameWithoutExtension(strScriptFile);
                    Array arrVersion = strScriptVersion.Split(new char[] { '.' });
                    int intMajor = Conversions.ToInteger(arrVersion.GetValue(0));
                    int intMinor = Conversions.ToInteger(arrVersion.GetValue(1));
                    int intBuild = Conversions.ToInteger(arrVersion.GetValue(2));
                    HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Upgrading to Version: " + intMajor.ToString() + "." + intMinor.ToString() + "." + intBuild.ToString() + "<br>");
                    if (!PortalSettings.FindDatabaseVersion(intMajor, intMinor, intBuild))
                    {
                        PortalSettings.UpgradeDatabaseSchema(intMajor, intMinor, intBuild);
                        strExceptions = ExecuteScript(strScriptFile, strScriptVersion);
                        PortalSettings.UpdateDatabaseVersion(intMajor, intMinor, intBuild);
                        EventLogController objEventLog = new EventLogController();
                        LogInfo objEventLogInfo = new LogInfo();
                        objEventLogInfo.AddProperty("Upgraded DotNetNuke", "Version: " + intMajor.ToString() + "." + intMinor.ToString() + "." + intBuild.ToString());
                        if (strExceptions.Length > 0)
                        {
                            objEventLogInfo.AddProperty("Warnings", strExceptions);
                        }
                        else
                        {
                            objEventLogInfo.AddProperty("No Warnings", "");
                        }
                        objEventLogInfo.LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString();
                        objEventLogInfo.BypassBuffering = true;
                    }
                }
            }
            finally
            {
                if (refObjectHelperL0 is IDisposable)
                {
                    (refObjectHelperL0 as IDisposable).Dispose();
                }
            }
            HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Performing General Upgrades<br>");
            strExceptions = UpgradeApplication();
            if (strExceptions != "")
            {
                EventLogController objEventLog = new EventLogController();
                LogInfo objEventLogInfo = new LogInfo();
                objEventLogInfo.AddProperty("Upgraded DotNetNuke", "General");
                objEventLogInfo.AddProperty("Warnings", strExceptions);
                objEventLogInfo.LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString();
                objEventLogInfo.BypassBuffering = true;
                objEventLog.AddLog(objEventLogInfo);
            }
            ArrayList arrPortals = new PortalController().GetPortals();
            int refIntHelperL1 = arrPortals.Count - 1;
            for (int j = 0; j <= refIntHelperL1; j++)
            {
                PortalInfo objPortal = (PortalInfo) arrPortals[j];
                DataCache.RemoveCache("GetTabPermissionsByPortal" + objPortal.PortalID.ToString());
            }
            if (Config.GetSetting("UseDnnConfig") == null)
            {
                useConfig = false;
            }
            else
            {
                useConfig = bool.Parse(Config.GetSetting("UseDnnConfig"));
            }
            if (useConfig)
            {
                DotNetNuke.Common.Globals.SaveDatabaseVersion(strAssemblyVersion);
            }
        }

        public static TimeSpan RunTime
        {
            get
            {
                return DateTime.Now.Subtract(startTime);
            }
        }
    }
}

